<template>
	<view class="bi-wx-login" :class="{'is-allow-submit': allowSubmit}" @click="handleClick">
		<view class="bi-wx-login__handle">
			<template v-if="fetching">
				获取认证信息中...
			</template>
			<template v-else>
				{{ loading ? '登录中...' : '一键登录' }}
			</template>
		</view>
		<button
			v-if="allowSubmit && !loading && !fetching"
			class="bi-wx-login__control"
			open-type="getPhoneNumber" 
			@getphonenumber="handleGetphonenumber" 
			hover-class="none"
		>一键登录</button>
	</view>
</template>

<script>
import { login, getCodeKey } from './api.js'
import { error, success } from '@/utils/message.js'

export default {
	name: 'WxLoginButton',
	props: {
		allowSubmit: {
			type: Boolean,
			default: true
		},
    inviteUserId:{
      type: String,
      default: ''
    }
	},
	data () {
		return {
			fetching: false,
			loading: false,
			codeKey: null
		}
	},
	created () {
		this.fetching = true
		uni.login({
			provider: 'weixin',
			success: (data) => {
				return getCodeKey(data.code).then(rs => {
          console.log('getCodeKey', rs)
					this.codeKey = rs.codeKey
				}).finally(() => {
					this.fetching = false
				})
			},
			fail: () => {
				this.fetching = false
			}
		})
	},
	methods: {
		handleClick () {
			if (!this.allowSubmit) {
				this.$emit('before-submit')
			}
		},
		/**
		 * 点击登录
		 */
		handleGetphonenumber(e) {
      //console.log("12222222222222222222222222222222222222222222",e)
			if (e.detail.encryptedData) {
				this.loading = true
				uni.login({
					provider: 'weixin',
					success: (data) => {
						return login({
							codeKey: this.codeKey,
							encryptedData: e.detail.encryptedData,
							offset: e.detail.iv,
              invitedNum: this.inviteUserId
            }).then(data => {
              console.log("login999999999999999999",data)
							this.$emit('success', data)
						}).finally(() => {
							this.loading = false
						})
					},
					fail: () => {
						this.loading = false
					}
				})
				
			}
		}
	}
} 
</script>

<style lang="less">
.bi-wx-login{
	position: relative;
	overflow: hidden;
	&:not(.is-allow-submit) {
		&:after {
			content: '';
			position: absolute;
			top: 0;
			bottom: 0;
			left: 0;
			right: 0;
			z-index: 100;
		}
	}
}
.bi-wx-login__handle{
	display: block;
	height: 46px;
	line-height: 46px;
	text-align: center;
	background-color: #28C445;
	color: #fff;
	border-radius: 23px;
	// &:before {
	// 	content: '';
	// 	width: 24px;
	// 	height: 24px;
	// 	display: inline-block;
	// 	// background: url('./icon.png') no-repeat 50% 50%;
	// 	vertical-align: top;
	// 	background-size: 22px;
	// 	margin-top: 11px;
	// 	margin-right: 10px;
	// }
}
.bi-wx-login__control {
	position: absolute;
	left: 0;
	top: 0;
	z-index: 3;
	opacity: 0;
	width: 100%;
}
</style>